package ljl.alg.jianzhioffer.round2;

public class _12_path_in_rectangle {
    
    /**
     * 又是 dfs 和 bfs 两种，这个还是 dfs 吧，bfs 不合适
     * */
    String word;
    char[][] board;
    public boolean exist(char[][] board, String word) {
        int m = board.length, n = board[0].length;
        this.word = word;
        this.board = board;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (check(i, j, 0))
                    return true;
            }
        }
        return false;
    }
    
    boolean check(int i, int j, int index) {
        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || word.charAt(index) != board[i][j])
            return false;
        if (index == word.length() - 1)
            return true;
        board[i][j] = 0;
        boolean res = check(i + 1, j, index + 1)
            || check(i, j + 1,index + 1)
            || check(i - 1, j,index + 1)
            || check(i, j - 1,index + 1)
            ;
        board[i][j] = word.charAt(index);
        return res;
    }
    
    
}
